package Model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * O(lg(n)) sort with QuickSort, performed once all stati been added
 * @author pieterc
 */
public class MessageContainer {


    private class MessageStatus {

        public StatusMessage sm;
        public boolean changed;

        public MessageStatus(StatusMessage sm) {
            this.sm = sm;
            this.changed = true;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final MessageStatus other = (MessageStatus) obj;
            if (!this.sm.getIdentification().equals(other.sm.getIdentification())) {
                return false;
            }
            return true;
        }

        @Override
        public int hashCode() {
            return super.hashCode();
        }
    }

    private ArrayList<MessageStatus> messages;
    private int count;
    private boolean sorted;
    private int lastIndex;

    public MessageContainer() {
        messages = new ArrayList<MessageStatus>(50);
        count = 0;
        sorted = false;
    }

    public boolean empty() {
        return count == 0;
    }

    public synchronized Object pop() {
        if (!empty()) {
            //last accessed index
            lastIndex = 0;
            // if unsorted, we should sort first
            if (!sorted) {
                System.out.println("sorting");
                Collections.sort(messages, new Comparator() {

                    public int compare(Object o1, Object o2) {
                        MessageStatus ms1 = (MessageStatus) o1;
                        MessageStatus ms2 = (MessageStatus) o2;
                        return (-1) * ms1.sm.getTime().compareTo(ms2.sm.getTime());
                    }
                });
                sorted = true;
            }
            MessageStatus s = messages.get(lastIndex);
            while (!s.changed && !empty()) {
                lastIndex++;
                s = messages.get(lastIndex);
            }
            s.changed = false;
            count--;
            return s.sm;
        } else {
            return null;
        }
    }

    public Object push(Object item) {
        sorted = false;
        MessageStatus ms = new MessageStatus((StatusMessage) item);
        if (messages.contains(ms)) {
            return null;
        } else {
            count++;
            messages.add(ms);
            return item;
        }
    }

    public int getLastIndex() {
        return lastIndex;
    }
}

